package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.mapper.OrderDetailMapper;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.BusinessDataVO;
import com.sky.vo.OrderReportVO;
import com.sky.vo.SalesTop10ReportVO;
import com.sky.vo.TurnoverReportVO;
import com.sky.vo.TurnoverSumVO;
import com.sky.vo.UserReportVO;

import org.apache.commons.lang.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

@Service
public class ReportServiceImpl implements ReportService {
    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private WorkspaceService workspaceService;

    /**
     * 查询销量排名top10
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public SalesTop10ReportVO top10(LocalDate begin, LocalDate end) {
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);
        //查询销量排名
        List<GoodsSalesDTO> goodsSalesDTOS = orderDetailMapper.getSaleTop(beginTime, endTime);
        //集合转换
        List<String> names = goodsSalesDTOS.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        List<Integer> numbers = goodsSalesDTOS.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());
        String nameList = StringUtils.join(names, ",");
        String numberList = StringUtils.join(numbers, ",");
        return SalesTop10ReportVO.builder().nameList(nameList).numberList(numberList).build();
    }

    @Override
    public OrderReportVO ordersStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> localDateList = new ArrayList<>();
        localDateList.add(begin);
        while (!begin.equals(end)) {
            //日期+1
            begin = begin.plusDays(1);
            localDateList.add(begin);
        }
        //日期列表
        String dateList = StringUtils.join(localDateList, ",");
        List<Integer> orderCounts = new ArrayList<>();
        List<Integer> validOrderCounts = new ArrayList<>();
        localDateList.forEach(date -> {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Map map = new HashMap();
            map.put("beginTime", beginTime);
            map.put("endTime", endTime);
            //查询某个日期的订单总数
            Integer totalCount = orderMapper.countByMap(map);
            orderCounts.add(totalCount);
            map.put("status", 5);
            //查询某个日期的有效订单总数
            Integer validCount = orderMapper.countByMap(map);
            validOrderCounts.add(validCount);

        });
        String orderCountList = StringUtils.join(orderCounts, ",");
        String validOrderCountList = StringUtils.join(validOrderCounts, ",");
        //集合各个元素累加
        Integer totalOrderCount = orderCounts.stream().reduce(Integer::sum).get();
        Integer validOrderCount = validOrderCounts.stream().reduce(Integer::sum).get();
        Double orderCompletionRate = totalOrderCount == null ? 0.00 : (validOrderCount.doubleValue() / totalOrderCount);

        return OrderReportVO.builder().dateList(dateList).orderCountList(orderCountList).validOrderCountList(validOrderCountList).totalOrderCount(totalOrderCount).validOrderCount(validOrderCount).orderCompletionRate(orderCompletionRate).build();


    }

    //有点BUG 通过分组查询 只能查询出 有金额数据的订单
    @Override
    public TurnoverReportVO turnoverStatistics(LocalDate begin, LocalDate end) {
        //求出某天的 起始时间点 和 结束时间点
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);
        Map map = new HashMap();
        map.put("beginTime", beginTime);
        map.put("endTime", endTime);
        List<TurnoverSumVO> voList = orderMapper.sumByMap(map);
        //集合转换
        List<String> dateList = voList.stream().map(TurnoverSumVO::getDate).collect(Collectors.toList());
        List<Double> turnoverList = voList.stream().map(TurnoverSumVO::getTurnover).collect(Collectors.toList());
        return TurnoverReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .turnoverList(StringUtils.join(turnoverList, ","))
                .build();
    }

    @Override
    public UserReportVO userStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dates = new ArrayList<>();
        dates.add(begin);
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dates.add(begin);
        }
        String dateList = StringUtils.join(dates, ",");
        List<Integer> newUserList = new ArrayList<>();
        List<Integer> totalUserList = new ArrayList<>();
        dates.forEach(date -> {
            //每天的起始时间 和开始时间  00:00:00  23:59:59
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Integer newUserCount = countByTime(beginTime, endTime);
            newUserList.add(newUserCount);
            Integer totalUserCount = countByTime(null, endTime);
            totalUserList.add(totalUserCount);

        });

        return UserReportVO
                .builder()
                .dateList(dateList)
                .newUserList(StringUtils.join(newUserList, ",")).
                totalUserList(StringUtils.join(totalUserList, ","))
                .build();
    }

    /**
     * 实现Excel 导出运营数据报表
     *
     * @param httpServletResponse
     */
    @Override
    public void export(HttpServletResponse httpServletResponse) {
        //1、查询营业数据
        //查询运营统计
        LocalDate localDate = LocalDate.now();
        LocalDate beginDate = localDate.minusDays(29);
        LocalDate endDate = localDate;
        LocalDateTime beginTime = LocalDateTime.of(beginDate, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(endDate, LocalTime.MAX);
        BusinessDataVO businessDataVO = workspaceService.businessData(beginTime, endTime);
        //2、写入exce文件
        //获取输入流
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");
        try {
            XSSFWorkbook xssfWorkbook = new XSSFWorkbook(inputStream);
            //获取Sheet页
            XSSFSheet xssfSheet = xssfWorkbook.getSheet("Sheet1");
            //第2行 第2列
            xssfSheet.getRow(1).getCell(1).setCellValue("时间：" + beginDate + "-" + endDate);

            xssfSheet.getRow(3).getCell(2).setCellValue(businessDataVO.getTurnover());
            xssfSheet.getRow(3).getCell(4).setCellValue(businessDataVO.getOrderCompletionRate());
            xssfSheet.getRow(3).getCell(6).setCellValue(businessDataVO.getNewUsers());
            xssfSheet.getRow(4).getCell(2).setCellValue(businessDataVO.getValidOrderCount());
            xssfSheet.getRow(4).getCell(4).setCellValue(businessDataVO.getUnitPrice());



            //4、明细数据
            for (int i = 0; i <30 ; i++) {
                //算出每一天的运营数据
                LocalDate date = beginDate.plusDays(i);
                LocalDateTime startTime = LocalDateTime.of(date, LocalTime.MIN);
                LocalDateTime stopTime = LocalDateTime.of(date, LocalTime.MAX);
                BusinessDataVO vo = workspaceService.businessData(startTime, stopTime);
                //第8行开始填充
                XSSFRow xssfRow = xssfSheet.getRow(7+i);
                xssfRow.getCell(1).setCellValue(date.toString());
                xssfRow.getCell(2).setCellValue(vo.getTurnover());
                xssfRow.getCell(3).setCellValue(vo.getValidOrderCount());
                xssfRow.getCell(4).setCellValue(vo.getOrderCompletionRate());
                xssfRow.getCell(5).setCellValue(vo.getUnitPrice());
                xssfRow.getCell(6).setCellValue(vo.getNewUsers());
            }
            //3、通过输出流  下载到客户端浏览器
            ServletOutputStream servletOutputStream = httpServletResponse.getOutputStream();
            xssfWorkbook.write(servletOutputStream);
            //5、关闭流
            servletOutputStream.close();
            xssfWorkbook.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }


    }

    private Integer countByTime(LocalDateTime beginTime, LocalDateTime endTime) {
        Map map = new HashMap();
        map.put("beginTime", beginTime);
        map.put("endTime", endTime);
        return userMapper.countByMap(map);
    }


}
